// 共享管理JavaScript模块 - 修复版

// 全局变量
let shareableUsers = [];
let shareableGroups = [];
let currentShareResource = null;
let myShares = [];
let accessibleShares = [];

// 共享模式状态
let sharedFolders = []; // 存储共享文件夹列表

// 🔧 修复日期格式化函数
function formatDateTimeSmart(dateTimeStr) {
    console.log('[DEBUG] formatDateTime 输入:', dateTimeStr, '类型:', typeof dateTimeStr);

    if (!dateTimeStr) {
        console.log('[DEBUG] 输入为空，返回永不过期');
        return '永不过期';
    }

    try {
        let dateObj;

        if (typeof dateTimeStr === 'string') {
            // 支持格式："YYYY-MM-DD HH:mm:ss" 或 "YYYY-MM-DD HH:mm:ss.0"
            const match = dateTimeStr.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})(\.\d+)?$/);
            if (match) {
                const year = parseInt(match[1], 10);
                const month = parseInt(match[2], 10) - 1;
                const day = parseInt(match[3], 10);
                const hour = parseInt(match[4], 10);
                const minute = parseInt(match[5], 10);
                const second = parseInt(match[6], 10);
                dateObj = new Date(year, month, day, hour, minute, second);
                console.log('[DEBUG] 手动构造 Date 对象:', dateObj);
            } else {
                console.warn('[DEBUG] 无法识别的时间字符串格式:', dateTimeStr);
                return '格式错误';
            }
        } else if (typeof dateTimeStr === 'object' && dateTimeStr.date && dateTimeStr.time) {
            const d = dateTimeStr.date;
            const t = dateTimeStr.time;
            dateObj = new Date(d.year, d.month - 1, d.day, t.hour || 0, t.minute || 0, t.second || 0);
            console.log('[DEBUG] 从LocalDateTime对象构造:', dateObj);
        } else {
            console.warn('[DEBUG] 未知的时间格式:', dateTimeStr);
            return '格式错误';
        }

        if (isNaN(dateObj.getTime())) {
            console.error('[DEBUG] 无效的日期对象:', dateObj);
            return '无效日期';
        }

        const y = dateObj.getFullYear();
        const m = ('0' + (dateObj.getMonth() + 1)).slice(-2);
        const d = ('0' + dateObj.getDate()).slice(-2);
        const h = ('0' + dateObj.getHours()).slice(-2);
        const min = ('0' + dateObj.getMinutes()).slice(-2);
        const s = ('0' + dateObj.getSeconds()).slice(-2);

        const formatted = y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s;
        console.log('[DEBUG] formatDateTime 输出:', formatted);
        return formatted;

    } catch (error) {
        console.error('[DEBUG] formatDateTime 错误:', error);
        return '格式错误';
    }
}

function parseDateTimeToObject(dateTimeStr) {
    if (!dateTimeStr) return null;

    if (typeof dateTimeStr === 'string') {
        const match = dateTimeStr.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/);
        if (match) {
            const year = parseInt(match[1], 10);
            const month = parseInt(match[2], 10) - 1;
            const day = parseInt(match[3], 10);
            const hour = parseInt(match[4], 10);
            const minute = parseInt(match[5], 10);
            const second = parseInt(match[6], 10);
            return new Date(year, month, day, hour, minute, second);
        }
    }
    return null;
}


// 🔧 新增：续期共享函数
function renewShare(shareId) {
    console.log('[DEBUG] 续期共享，ID:', shareId);
    
    if (!confirm('确定要延长此共享的有效期吗？')) {
        return;
    }
    
    // 显示续期选项对话框
    showRenewShareDialog(shareId);
}

// 🔧 新增：显示续期对话框
function showRenewShareDialog(shareId) {
    const modalHtml = `
        <div id="renewShareModal" class="modal" style="display: block;">
            <div class="modal-content">
                <div class="modal-header">
                    <h2><i class="fas fa-clock"></i> 延长共享期限</h2>
                    <span class="close" onclick="hideModal('renewShareModal')">&times;</span>
                </div>
                <form id="renewShareForm">
                    <div class="form-group">
                        <label for="renewPeriod">延长期限</label>
                        <select id="renewPeriod" name="renewPeriod" required>
                            <option value="1hour">1小时</option>
                            <option value="1day" selected>1天</option>
                            <option value="1week">1周</option>
                            <option value="1month">1个月</option>
                            <option value="never">永不过期</option>
                        </select>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="hideModal('renewShareModal')">取消</button>
                        <button type="submit" class="btn btn-primary">确认续期</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 绑定表单提交事件
    document.getElementById('renewShareForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const renewPeriod = document.getElementById('renewPeriod').value;
        executeRenewShare(shareId, renewPeriod);
    });
}

// 🔧 新增：执行续期操作
function executeRenewShare(shareId, renewPeriod) {
    console.log('[DEBUG] 执行续期操作，shareId:', shareId, 'period:', renewPeriod);
    
    showLoader();
    
    const formData = new FormData();
    formData.append('action', 'renewShare');
    formData.append('shareId', shareId);
    formData.append('renewPeriod', renewPeriod);
    
    fetch('ShareManagementServlet', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('[DEBUG] 续期响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        hideLoader();
        console.log('[DEBUG] 续期响应数据:', data);
        
        if (data.success) {
            showMessage('共享期限已成功延长', 'success');
            hideModal('renewShareModal');
            // 移除续期对话框
            const renewModal = document.getElementById('renewShareModal');
            if (renewModal) {
                renewModal.remove();
            }
            // 重新加载共享列表
            loadMyShares();
        } else {
            showMessage('续期失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('[DEBUG] 续期请求失败:', error);
        showMessage('续期失败: ' + error.message, 'error');
    });
}

// 初始化共享功能
function initShareManagement() {
    console.log('初始化共享管理功能...');
    
    // 加载可共享的用户和用户组
    loadShareableUsers();
    loadShareableGroups();
    
    // 绑定共享相关事件
    bindShareEvents();
    
    // 定期检查共享通知
    setInterval(checkShareNotifications, 60000); // 每分钟检查一次
    checkShareNotifications(); // 立即检查一次
}

// 绑定共享事件
function bindShareEvents() {
    console.log('[DEBUG] 开始绑定共享事件...');
    
    // 先移除可能存在的旧事件监听器，防止重复绑定
    const shareCard = document.getElementById('shareCard');
    const shareFolder = document.getElementById('shareFolder');
    const manageShares = document.getElementById('manageShares');
    const viewSharedWithMe = document.getElementById('viewSharedWithMe');
    
    // 移除旧的事件监听器（通过克隆节点的方式）
    function removeAllEventListeners(element) {
        if (element && element.parentNode) {
            const newElement = element.cloneNode(true);
            element.parentNode.replaceChild(newElement, element);
            return newElement;
        }
        return element;
    }
    
    // 共享名片按钮事件 - 只绑定一次
    if (shareCard) {
        const newShareCard = removeAllEventListeners(shareCard);
        newShareCard.addEventListener('click', (e) => {
            e.preventDefault();
            if (!checkPermissionBeforeAction('share_cards', '分享名片')) {
                return;
            }
            
            if (selectedCardIds.length > 0) {
                showShareDialog('card', selectedCardIds);
            } else {
                showMessage('请先选择要分享的名片', 'error');
            }
        });
    }
    
    // 共享名片夹按钮事件 - 只绑定一次
    if (shareFolder) {
        const newShareFolder = removeAllEventListeners(shareFolder);
        newShareFolder.addEventListener('click', (e) => {
            e.preventDefault();
            if (!checkPermissionBeforeAction('share_folders', '分享名片夹')) {
                return;
            }
            
            if (currentFolder) {
                showShareDialog('folder', [currentFolder]);
            } else {
                showMessage('请先选择要分享的名片夹', 'error');
            }
        });
    }
    
    // 管理共享按钮事件 - 只绑定一次
    if (manageShares) {
        const newManageShares = removeAllEventListeners(manageShares);
        newManageShares.addEventListener('click', (e) => {
            e.preventDefault();
            if (!checkPermissionBeforeAction('manage_shares', '管理共享')) {
                return;
            }
            showShareManagementModal();
        });
    }
    
    // 查看共享给我的内容 - 只绑定一次
    if (viewSharedWithMe) {
        const newViewSharedWithMe = removeAllEventListeners(viewSharedWithMe);
        newViewSharedWithMe.addEventListener('click', (e) => {
            e.preventDefault();
            showSharedWithMeModal();
        });
    }
    
    // 共享表单提交事件 - 只绑定一次
    const shareForm = document.getElementById('shareForm');
    if (shareForm) {
        const newShareForm = removeAllEventListeners(shareForm);
        newShareForm.addEventListener('submit', (e) => {
            e.preventDefault();
            console.log('[DEBUG] 共享表单提交事件触发');
            handleShareSubmit();
        });
    }
    
    // 共享类型变化事件
    document.querySelectorAll('input[name="shareType"]').forEach(radio => {
        radio.removeEventListener('change', handleShareTypeChange); // 先移除
        radio.addEventListener('change', handleShareTypeChange);     // 再添加
    });
    
    console.log('[DEBUG] 共享事件绑定完成');
}

// 显示共享对话框
function showShareDialog(resourceType, resourceIds) {
    console.log('[DEBUG] 显示共享对话框');
    console.log('[DEBUG] 资源类型:', resourceType);
    console.log('[DEBUG] 资源IDs:', resourceIds);
    console.log('[DEBUG] 当前用户ID:', currentUserId);
    console.log('[DEBUG] 当前文件夹:', currentFolder);
    
    currentShareResource = {
        type: resourceType,
        ids: resourceIds
    };
    
    // 设置对话框标题
    const title = resourceType === 'card' ? '分享名片' : '分享名片夹';
    document.querySelector('#shareModal .modal-header h2').textContent = title;
    
    // 设置资源信息
    const resourceInfo = document.getElementById('shareResourceInfo');
    if (resourceType === 'card') {
        resourceInfo.textContent = '将分享 ' + resourceIds.length + ' 张名片';
    } else {
        const folderName = getCurrentFolderName();
        resourceInfo.textContent = '将分享名片夹: ' + folderName;
    }
    
    // 重置表单
    document.getElementById('shareForm').reset();
    updateShareTargetOptions();
    
    console.log('[DEBUG] 共享对话框设置完成');
    showModal('shareModal');
}

// 处理共享类型变化
function handleShareTypeChange(e) {
    updateShareTargetOptions();
}

// 更新共享目标选项
function updateShareTargetOptions() {
    const shareType = document.querySelector('input[name="shareType"]:checked').value;
    const targetSelect = document.getElementById('shareTarget');
    
    targetSelect.innerHTML = '<option value="">请选择...</option>';
    targetSelect.disabled = shareType === 'public';
    
    if (shareType === 'user') {
        shareableUsers.forEach(user => {
            const option = document.createElement('option');
            option.value = user.userId;
            option.textContent = user.username + ' (' + user.email + ')';
            targetSelect.appendChild(option);
        });
    } else if (shareType === 'group') {
        shareableGroups.forEach(group => {
            const option = document.createElement('option');
            option.value = group.groupId;
            option.textContent = group.groupName;
            targetSelect.appendChild(option);
        });
    }
}

// 修复重复插入问题 - 改进的共享表单提交处理
let isSubmittingShare = false; // 防止重复提交的标志

function handleShareSubmit() {
    console.log('[DEBUG] 开始处理共享表单提交');
    
    // 防止重复提交
    if (isSubmittingShare) {
        console.log('[DEBUG] 共享正在提交中，忽略重复请求');
        return;
    }
    
    // 设置提交标志
    isSubmittingShare = true;
    
    const formData = new FormData(document.getElementById('shareForm'));
    
    // 打印所有表单数据
    console.log('[DEBUG] 表单数据:');
    for (let [key, value] of formData.entries()) {
        console.log(`  ${key}: ${value}`);
    }
    
    const shareData = {
        resourceType: currentShareResource.type,
        resourceIds: JSON.stringify(currentShareResource.ids),
        shareType: formData.get('shareType'),
        permissionLevel: formData.get('permissionLevel'),
        expiresIn: formData.get('expiresIn')
    };
    
    console.log('[DEBUG] 当前共享资源:', currentShareResource);
    console.log('[DEBUG] 准备发送的数据:', shareData);
    
    // 如果不是公开分享，需要指定目标
    if (shareData.shareType !== 'public') {
        const targetId = formData.get('shareTarget');
        console.log('[DEBUG] 目标ID:', targetId);
        if (!targetId) {
            console.error('[DEBUG] 缺少分享目标');
            showMessage('请选择分享目标', 'error');
            isSubmittingShare = false; // 重置标志
            return;
        }
        shareData.targetId = targetId;
    }
    
    createShare(shareData);
}

// 创建共享
function createShare(shareData) {
    console.log('[DEBUG] 开始创建共享');
    
    showLoader();
    
    // 解析资源IDs并去重
    let resourceIds;
    try {
        resourceIds = JSON.parse(shareData.resourceIds);
        // 去重处理 - 转换为Set再转回数组
        resourceIds = [...new Set(resourceIds)];
        console.log('[DEBUG] 去重后的资源IDs:', resourceIds);
    } catch (error) {
        console.error('[DEBUG] 解析资源IDs失败:', error);
        hideLoader();
        isSubmittingShare = false;
        showMessage('资源ID格式错误', 'error');
        return;
    }
    
    if (!resourceIds || resourceIds.length === 0) {
        console.error('[DEBUG] 没有有效的资源ID');
        hideLoader();
        isSubmittingShare = false;
        showMessage('没有选择要共享的资源', 'error');
        return;
    }
    
    let completedCount = 0;
    let successCount = 0;
    
    // 为每个资源创建共享记录
    resourceIds.forEach((resourceId, index) => {
        console.log(`[DEBUG] 处理第${index + 1}个资源, ID: ${resourceId}`);
        
        const formData = new FormData();
        formData.append('action', 'createShare');
        formData.append('resourceType', shareData.resourceType);
        formData.append('resourceId', resourceId);
        formData.append('shareType', shareData.shareType);
        formData.append('permissionLevel', shareData.permissionLevel);
        formData.append('expiresIn', shareData.expiresIn);
        
        if (shareData.targetId) {
            formData.append('targetId', shareData.targetId);
        }
        
        // 打印发送给服务器的数据
        console.log(`[DEBUG] 发送给服务器的数据 (资源${resourceId}):`);
        for (let [key, value] of formData.entries()) {
            console.log(`  ${key}: ${value}`);
        }
        
        fetch('ShareManagementServlet', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            console.log(`[DEBUG] 服务器响应状态 (资源${resourceId}):`, response.status);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            console.log(`[DEBUG] 服务器响应数据 (资源${resourceId}):`, data);
            
            if (data.success) {
                successCount++;
                console.log(`[DEBUG] 资源${resourceId}共享成功`);
            } else {
                console.error(`[DEBUG] 资源${resourceId}共享失败:`, data.message);
            }
            completedCount++;
            
            // 所有请求完成后的处理
            if (completedCount === resourceIds.length) {
                console.log(`[DEBUG] 所有资源处理完成. 成功: ${successCount}, 总数: ${resourceIds.length}`);
                handleCreateShareComplete(successCount, resourceIds.length);
            }
        })
        .catch(error => {
            console.error(`[DEBUG] 资源${resourceId}请求失败:`, error);
            completedCount++;
            
            if (completedCount === resourceIds.length) {
                handleCreateShareComplete(successCount, resourceIds.length, error);
            }
        });
    });
}

// 共享创建完成的统一处理函数
function handleCreateShareComplete(successCount, totalCount, error = null) {
    hideLoader();
    isSubmittingShare = false; // 重置提交标志
    hideModal('shareModal');
    
    if (error && successCount === 0) {
        showMessage('创建共享时发生错误: ' + error.message, 'error');
    } else if (successCount > 0) {
        showMessage('成功创建 ' + successCount + ' 个共享', 'success');
        // 清空选中状态
        selectedCardIds = [];
        updateSelectAllState();
    } else {
        showMessage('创建共享失败', 'error');
    }
}

// 加载可共享的用户
function loadShareableUsers() {
    fetch('ShareManagementServlet?action=getShareableUsers')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                shareableUsers = data.users || [];
            }
        })
        .catch(error => {
            console.error('加载可共享用户失败:', error);
        });
}

// 加载可共享的用户组
function loadShareableGroups() {
    fetch('ShareManagementServlet?action=getShareableGroups')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                shareableGroups = data.groups || [];
            }
        })
        .catch(error => {
            console.error('加载可共享用户组失败:', error);
        });
}

// 显示共享管理模态框
function showShareManagementModal() {
    loadMyShares();
    showModal('shareManagementModal');
}

// 加载我的共享
function loadMyShares() {
    console.log('[DEBUG] ===== 开始加载我的共享 =====');
    showLoader();
    
    fetch('ShareManagementServlet?action=getMyShares')
        .then(response => {
            console.log('[DEBUG] 响应状态:', response.status);
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.text(); // 先获取原始文本
        })
        .then(text => {
            console.log('[DEBUG] 原始响应文本:', text);
            try {
                const data = JSON.parse(text);
                console.log('[DEBUG] 解析后的JSON:', data);
                return data;
            } catch (e) {
                console.error('[DEBUG] JSON解析失败:', e);
                throw new Error('响应不是有效的JSON格式');
            }
        })
        .then(data => {
            hideLoader();
            
            if (data.success) {
                myShares = data.shares || [];
                console.log('[DEBUG] 获取到的共享数量:', myShares.length);
                
                // 详细检查每个共享对象
                myShares.forEach((share, index) => {
                    console.log('[DEBUG] ===== 共享对象', index + 1, '=====');
                    console.log('shareId:', share.shareId);
                    console.log('resourceName:', share.resourceName);
                    console.log('targetName:', share.targetName);
                    console.log('expiresAt 原始值:', share.expiresAt);
                    console.log('expiresAt 类型:', typeof share.expiresAt);
                    console.log('createdAt 原始值:', share.createdAt);
                    console.log('createdAt 类型:', typeof share.createdAt);
                    
                    // 测试格式化
                    const formattedExpires = formatDateTimeSmart(share.expiresAt);
                    const formattedCreated = formatDateTimeSmart(share.createdAt);
                    console.log('格式化后 expiresAt:', formattedExpires);
                    console.log('格式化后 createdAt:', formattedCreated);
                });
                
                renderMyShares();
            } else {
                console.error('[DEBUG] 服务器返回失败:', data.message);
                showMessage('加载共享列表失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            hideLoader();
            console.error('[DEBUG] 加载我的共享失败:', error);
            showMessage('加载共享列表失败: ' + error.message, 'error');
        });
}

// 渲染我的共享列表
function renderMyShares() {
    console.log('[DEBUG] ===== 开始渲染共享列表 =====');
    
    const container = document.getElementById('mySharesList');
    container.innerHTML = '';
    
    if (myShares.length === 0) {
        container.innerHTML = '<p class="empty-message">暂无共享内容</p>';
        return;
    }
    
    myShares.forEach((share, index) => {
        console.log('[DEBUG] 渲染第', index + 1, '个共享:', share.resourceName);
        
        const shareItem = document.createElement('div');
        shareItem.className = 'share-item';
        
        const typeIcon = share.resourceType === 'CARD' ? 'fas fa-id-card' : 'fas fa-folder';
        const typeText = share.resourceType === 'CARD' ? '名片' : '名片夹';
        const permissionText = share.permissionLevel === 'READ' ? '只读' : '编辑';
        const shareTypeText = getShareTypeText(share.shareType, share.targetName);
        
        // 🔧 使用修复后的时间格式化
        const expiresText = formatDateTimeSmart(share.expiresAt);
        const createdText = formatDateTimeSmart(share.createdAt);
        
        console.log('[DEBUG] 第', index + 1, '个共享的时间格式化结果:');
        console.log('  过期时间:', share.expiresAt, '->', expiresText);
        console.log('  创建时间:', share.createdAt, '->', createdText);
        
        // 检查是否过期（使用原始时间进行比较）
        let isExpired = false;
        if (share.expiresAt) {
            try {
            	const expiryDate = parseDateTimeToObject(share.expiresAt);
            	isExpired = expiryDate && expiryDate < new Date();
                console.log('[DEBUG] 过期检查:', expiryDate, '<', new Date(), '=', isExpired);
            } catch (e) {
                console.warn('[DEBUG] 过期时间检查失败:', e);
            }
        }
        
        if (isExpired) {
            shareItem.classList.add('expired-share');
            shareItem.style.opacity = '0.6';
            shareItem.style.border = '1px solid #dc3545';
        }
        
        shareItem.innerHTML = [
            '<div class="share-item-header">',
                '<i class="' + typeIcon + '"></i>',
                '<span class="share-resource-name">' + (share.resourceName || '') + '</span>',
                '<span class="share-type-badge">' + typeText + '</span>',
                isExpired ? '<span class="expired-badge" style="background: #dc3545; color: white; padding: 2px 6px; border-radius: 10px; font-size: 10px;">已过期</span>' : '',
            '</div>',
            '<div class="share-item-details">',
                '<div class="share-detail-item">',
                    '<span class="label">共享给:</span>',
                    '<span class="value">' + shareTypeText + '</span>',
                '</div>',
                '<div class="share-detail-item">',
                    '<span class="label">权限:</span>',
                    '<span class="value">' + permissionText + '</span>',
                '</div>',
                '<div class="share-detail-item">',
                    '<span class="label">过期时间:</span>',
                    '<span class="value">' + expiresText + '</span>',
                '</div>',
                '<div class="share-detail-item">',
                    '<span class="label">创建时间:</span>',
                    '<span class="value">' + createdText + '</span>',
                '</div>',
            '</div>',
            '<div class="share-item-actions">',
                '<button class="btn btn-secondary btn-sm" onclick="viewShareLogs(' + share.shareId + ')">',
                    '<i class="fas fa-history"></i> 日志',
                '</button>',
                isExpired ? ('<button class="btn btn-warning btn-sm" onclick="renewShare(' + share.shareId + ')">' +
                    '<i class="fas fa-clock"></i> 续期</button>') : '',
                '<button class="btn btn-danger btn-sm" onclick="revokeShare(' + share.shareId + ')">',
                    '<i class="fas fa-times"></i> 撤销',
                '</button>',
            '</div>'
        ].join('');
        
        container.appendChild(shareItem);
    });
    
    console.log('[DEBUG] ===== 共享列表渲染完成 =====');
}

// 获取共享类型文本
function getShareTypeText(shareType, targetName) {
    switch (shareType) {
        case 'PUBLIC':
            return '公开共享';
        case 'USER':
            return '用户: ' + (targetName || '未知用户');
        case 'GROUP':
            return '用户组: ' + (targetName || '未知用户组');
        default:
            return '未知';
    }
}

// 撤销共享
function revokeShare(shareId) {
    if (!confirm('确定要撤销此共享吗？')) {
        return;
    }
    
    showLoader();
    
    const formData = new FormData();
    formData.append('action', 'revokeShare');
    formData.append('shareId', shareId);
    
    fetch('ShareManagementServlet', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        hideLoader();
        if (data.success) {
            showMessage('共享已撤销', 'success');
            loadMyShares(); // 重新加载列表
        } else {
            showMessage('撤销共享失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('撤销共享失败:', error);
        showMessage('撤销共享失败', 'error');
    });
}

// 查看共享日志
function viewShareLogs(shareId) {
    fetch('ShareManagementServlet?action=getShareLogs&shareId=' + shareId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showShareLogsModal(data.logs);
            } else {
                showMessage('获取共享日志失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('获取共享日志失败:', error);
            showMessage('获取共享日志失败', 'error');
        });
}

// 显示共享日志模态框
function showShareLogsModal(logs) {
    const container = document.getElementById('shareLogsList');
    container.innerHTML = '';
    
    if (logs.length === 0) {
        container.innerHTML = '<p class="empty-message">暂无日志记录</p>';
    } else {
        logs.forEach(log => {
            const logItem = document.createElement('div');
            logItem.className = 'log-item';
            
            const actionText = getActionText(log.action);
            const actionIcon = getActionIcon(log.action);
            
            logItem.innerHTML = `
                <div class="log-item-header">
                    <i class="${actionIcon}"></i>
                    <span class="log-action">${actionText}</span>
                    <span class="log-time">${formatDateTimeSmart(log.createdAt)}</span>
                </div>
                <div class="log-details">
                    <div class="log-user">用户: ${log.username}</div>
                    <div class="log-ip">IP: ${log.ipAddress}</div>
                    <div class="log-description">${log.details}</div>
                </div>
            `;
            
            container.appendChild(logItem);
        });
    }
    
    showModal('shareLogsModal');
}

// 获取操作文本
function getActionText(action) {
    const actionMap = {
        'CREATE': '创建共享',
        'UPDATE': '更新共享',
        'DELETE': '删除共享',
        'ACCESS': '访问资源',
        'EDIT': '编辑资源',
        'REVOKE': '撤销共享'
    };
    return actionMap[action] || action;
}

// 获取操作图标
function getActionIcon(action) {
    const iconMap = {
        'CREATE': 'fas fa-plus-circle text-success',
        'UPDATE': 'fas fa-edit text-primary',
        'DELETE': 'fas fa-trash text-danger',
        'ACCESS': 'fas fa-eye text-info',
        'EDIT': 'fas fa-pencil-alt text-warning',
        'REVOKE': 'fas fa-times-circle text-danger'
    };
    return iconMap[action] || 'fas fa-info-circle';
}

// 显示共享给我的内容模态框
function showSharedWithMeModal() {
    loadAccessibleShares();
    showModal('sharedWithMeModal');
}

// 加载可访问的共享内容 - 修复版
function loadAccessibleShares() {
    console.log('[DEBUG] 开始加载可访问的共享内容');
    showLoader();
    
    fetch('ShareManagementServlet?action=getAccessibleShares')
        .then(response => response.json())
        .then(data => {
            hideLoader();
            console.log('[DEBUG] 获取共享内容响应:', data);
            
            if (data.success) {
                accessibleShares = data.shares || [];
                console.log('[DEBUG] 可访问的共享数量:', accessibleShares.length);
                renderAccessibleShares();
                
                // 更新共享文件夹列表
                updateSharedFoldersList();
            } else {
                console.error('[DEBUG] 获取共享内容失败:', data.message);
                showMessage('加载共享内容失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            hideLoader();
            console.error('[DEBUG] 加载可访问共享失败:', error);
            showMessage('加载共享内容失败', 'error');
        });
}

// 更新共享文件夹列表
function updateSharedFoldersList() {
    sharedFolders = accessibleShares
        .filter(share => share.resourceType === 'FOLDER')
        .map(share => ({
            id: share.resourceId,
            name: share.resourceName,
            ownerName: share.ownerName,
            permissionLevel: share.permissionLevel
        }));
    
    console.log('[DEBUG] 共享文件夹列表:', sharedFolders);
}

// 渲染可访问的共享内容
//1. 修复 renderAccessibleShares 函数中的权限判断
//1. 修复 renderAccessibleShares 函数，确保权限信息正确显示
function renderAccessibleShares() {
    const container = document.getElementById('accessibleSharesList');
    container.innerHTML = '';
    
    if (accessibleShares.length === 0) {
        container.innerHTML = '<p class="empty-message">暂无共享内容</p>';
        return;
    }
    
    accessibleShares.forEach(share => {
        const shareItem = document.createElement('div');
        shareItem.className = 'accessible-share-item';
        
        const typeIcon = share.resourceType === 'CARD' ? 'fas fa-id-card' : 'fas fa-folder';
        const typeText = share.resourceType === 'CARD' ? '名片' : '名片夹';
        
        // 🔧 核心修复：确保权限信息正确识别和显示
        console.log('[DEBUG] 渲染共享项权限信息:', {
            resourceName: share.resourceName,
            permissionLevel: share.permissionLevel,
            resourceType: share.resourceType
        });
        
        const isReadOnly = share.permissionLevel === 'read' || share.permissionLevel === 'READ';
        const permissionText = isReadOnly ? '只读' : '编辑';
        const permissionClass = isReadOnly ? 'read-only' : 'editable';
        
        const expiresText = formatDateTimeSmart(share.expiresAt);
        
        shareItem.innerHTML = [
            '<div class="share-item-header">',
                '<div class="share-icon-wrapper">',
                    '<i class="' + typeIcon + '"></i>',
                '</div>',
                '<div class="share-main-info">',
                    '<span class="share-resource-name">' + (share.resourceName || '') + '</span>',
                    '<span class="share-type-badge">' + typeText + '</span>',
                '</div>',
                '<div class="share-permission-badge ' + permissionClass + '">',
                    '<i class="fas ' + (isReadOnly ? 'fa-eye' : 'fa-edit') + '"></i>',
                    permissionText,
                '</div>',
            '</div>',
            '<div class="share-item-details">',
                '<div class="share-detail-row">',
                    '<div class="share-detail-item">',
                        '<i class="fas fa-user"></i>',
                        '<span class="label">分享者:</span>',
                        '<span class="value">' + (share.ownerName || '') + '</span>',
                    '</div>',
                    '<div class="share-detail-item">',
                        '<i class="fas fa-clock"></i>',
                        '<span class="label">过期时间:</span>',
                        '<span class="value">' + expiresText + '</span>',
                    '</div>',
                '</div>',
            '</div>',
            '<div class="share-item-actions">',
                '<button class="btn btn-primary btn-access" onclick="accessSharedResource(\'' + share.resourceType + '\', ' + share.resourceId + ', \'' + share.permissionLevel + '\')">',
                    '<i class="fas fa-folder-open"></i> 访问',
                '</button>',
            '</div>'
        ].join('');
        
        container.appendChild(shareItem);
    });
}

//2. 修改 accessSharedResource 函数，传递权限信息
function accessSharedResource(resourceType, resourceId, permissionLevel) {
    console.log('[DEBUG] 访问共享资源:', resourceType, resourceId, '权限:', permissionLevel);
    
    // 记录访问日志
    logShareAccess(resourceType, resourceId);
    
    if (resourceType === 'CARD') {
        // 传递权限信息到单名片访问函数
        accessSharedCardWithPermission(resourceId, permissionLevel);
    } else if (resourceType === 'FOLDER') {
        // 传递权限信息到文件夹访问函数
        accessSharedFolderWithPermission(resourceId, permissionLevel);
    }
}

//3. 新增：带权限信息的单名片访问函数
function accessSharedCardWithPermission(cardId, permissionLevel) {
    console.log('[DEBUG] 访问共享名片，ID:', cardId, '权限:', permissionLevel);
    
    // 获取完整的共享信息
    const shareInfo = accessibleShares.find(share => 
        share.resourceType === 'CARD' && share.resourceId == cardId
    );
    
    if (!shareInfo) {
        showMessage('找不到共享权限信息', 'error');
        return;
    }
    
    // 设置共享模式状态，包含完整的权限信息
    isInSharedMode = true;
    sharedResourceInfo = {
        type: 'CARD',
        id: cardId,
        permissionLevel: permissionLevel || shareInfo.permissionLevel, // 确保权限信息存在
        ownerName: shareInfo.ownerName,
        resourceName: shareInfo.resourceName
    };
    
    console.log('[DEBUG] 设置的共享资源信息:', sharedResourceInfo);
    
    showLoader();
    
    // 获取名片详情
    fetch('BusinessCardServlet?action=getCardById&cardId=' + cardId)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(card => {
            hideLoader();
            
            if (card) {
                // 渲染简约版共享名片
                renderSharedCard(card);
                
                // 更新UI状态显示为共享模式
                updateUIForSharedMode('card', card.name);
                
                hideModal('sharedWithMeModal');
                
                // 显示访问成功消息
                const isReadOnly = (permissionLevel === 'read' || permissionLevel === 'READ');
                const permissionText = isReadOnly ? '只读' : '可编辑';
                showMessage('已打开共享名片: ' + card.name + ' (' + permissionText + ')', 'success');
            } else {
                throw new Error('名片不存在或已被删除');
            }
        })
        .catch(error => {
            hideLoader();
            console.error('访问共享名片失败:', error);
            showMessage('访问共享名片失败: ' + error.message, 'error');
        });
}

// 4. 新增：带权限信息的文件夹访问函数
function accessSharedFolderWithPermission(folderId, permissionLevel) {
    console.log('[DEBUG] 访问共享名片夹，ID:', folderId, '权限:', permissionLevel);
    
    // 设置共享模式状态
    isInSharedMode = true;
    sharedResourceInfo = {
        type: 'FOLDER',
        id: folderId,
        permissionLevel: permissionLevel
    };
    
    // 正常加载名片夹
    loadCards(folderId);
    currentFolder = folderId;
    
    // 获取共享文件夹信息
    const sharedFolder = sharedFolders.find(folder => folder.id === folderId);
    const folderName = sharedFolder ? sharedFolder.name : '共享名片夹';
    
    // 添加共享文件夹到UI
    addSharedFolderToUI(folderId, folderName, permissionLevel);
    
    // 更新UI为共享模式
    updateUIForSharedMode('folder', folderName);
    
    hideModal('sharedWithMeModal');
    
    // 显示访问成功消息
    const isReadOnly = (permissionLevel === 'read' || permissionLevel === 'READ');
    showMessage('已切换到共享名片夹: ' + folderName + ' (' + (isReadOnly ? '只读' : '可编辑') + ')', 'success');
}



//访问共享的单个名片 - 修复权限设置
function accessSharedCard(cardId) {
 console.log('[DEBUG] 访问共享名片，ID:', cardId);
 
 // 首先从 accessibleShares 中获取权限信息
 const shareInfo = accessibleShares.find(share => 
     share.resourceType === 'CARD' && share.resourceId == cardId
 );
 
 if (!shareInfo) {
     showMessage('找不到共享权限信息', 'error');
     return;
 }
 
 console.log('[DEBUG] 找到的共享信息:', shareInfo);
 
 // 设置共享模式状态，包含完整的权限信息
 isInSharedMode = true;
 sharedResourceInfo = {
     type: 'CARD',
     id: cardId,
     permissionLevel: shareInfo.permissionLevel, // 🔧 关键修复：设置权限级别
     ownerName: shareInfo.ownerName,
     resourceName: shareInfo.resourceName
 };
 
 console.log('[DEBUG] 设置的共享资源信息:', sharedResourceInfo);
 
 showLoader();
 
 // 获取这张特定名片的信息
 fetch('BusinessCardServlet?action=getCardById&cardId=' + cardId)
     .then(response => {
         if (!response.ok) {
             throw new Error('网络响应不正常');
         }
         return response.json();
     })
     .then(card => {
         hideLoader();
         
         if (card) {
             // 只渲染这一张名片，不加载整个名片夹
             renderSharedCard(card);
             
             // 更新UI状态显示为共享模式
             updateUIForSharedMode('card', card.name);
             
             hideModal('sharedWithMeModal');
             
             // 🔧 修复：正确显示权限信息
             const isReadOnly = shareInfo.permissionLevel === 'read' || shareInfo.permissionLevel === 'READ';
             const permissionText = isReadOnly ? '只读' : '可编辑';
             showMessage('已打开共享名片: ' + card.name + ' (' + permissionText + ')', 'success');
         } else {
             throw new Error('名片不存在或已被删除');
         }
     })
     .catch(error => {
         hideLoader();
         console.error('访问共享名片失败:', error);
         showMessage('访问共享名片失败: ' + error.message, 'error');
     });
}

// 访问共享的名片夹 - 修复版
function accessSharedFolder(folderId) {
    console.log('[DEBUG] 访问共享名片夹，ID:', folderId);
    
    // 设置共享模式状态
    isInSharedMode = true;
    sharedResourceInfo = {
        type: 'FOLDER',
        id: folderId
    };
    
    // 正常加载名片夹（原有逻辑）
    loadCards(folderId);
    currentFolder = folderId;
    
    // 获取共享文件夹信息
    const sharedFolder = sharedFolders.find(folder => folder.id === folderId);
    const folderName = sharedFolder ? sharedFolder.name : '共享名片夹';
    const permissionLevel = sharedFolder ? sharedFolder.permissionLevel : 'read';
    
    // 更新共享权限信息
    sharedResourceInfo.permissionLevel = permissionLevel;
    
    // 添加共享文件夹到UI
    addSharedFolderToUI(folderId, folderName, permissionLevel);
    
    // 更新UI为共享模式
    updateUIForSharedMode('folder', folderName);
    
    hideModal('sharedWithMeModal');
    
    // 🔧 核心修复：正确显示权限信息
    const isReadOnly = permissionLevel === 'read' || permissionLevel === 'READ';
    showMessage('已切换到共享名片夹: ' + folderName + ' (' + (isReadOnly ? '只读' : '可编辑') + ')', 'success');
}

// 添加共享文件夹到UI
function addSharedFolderToUI(folderId, folderName, permissionLevel) {
    const container = document.getElementById('cardFolders');
    const addButton = document.getElementById('addFolderBtn');
    
    // 检查是否已经存在
    const existingFolder = document.querySelector(`.card-folder[data-id="${folderId}"][data-shared="true"]`);
    if (existingFolder) {
        existingFolder.classList.add('active');
        return;
    }
    
    // 🔧 核心修复：正确判断权限
    const isReadOnly = permissionLevel === 'read' || permissionLevel === 'READ';
    
    // 创建共享文件夹元素
    const sharedFolderEl = document.createElement('div');
    sharedFolderEl.className = 'card-folder shared-folder active';
    sharedFolderEl.dataset.id = folderId;
    sharedFolderEl.dataset.name = folderName;
    sharedFolderEl.dataset.shared = 'true';
    sharedFolderEl.dataset.permission = permissionLevel;
    
    // 根据权限使用不同的样式
    const folderColor = isReadOnly ? '#ff9800' : '#4caf50';
    const permissionIcon = isReadOnly ? 'fa-eye' : 'fa-edit';
    const permissionText = isReadOnly ? '只读' : '可编辑';
    
    // 设置样式和内容
    sharedFolderEl.style.background = `linear-gradient(135deg, ${folderColor}, ${folderColor}dd)`;
    sharedFolderEl.style.color = 'white';
    sharedFolderEl.style.position = 'relative';
    sharedFolderEl.style.overflow = 'hidden';
    
    sharedFolderEl.innerHTML = `
        <div style="display: flex; align-items: center; justify-content: center; height: 100%; position: relative;">
            <div style="display: flex; flex-direction: column; align-items: center; text-align: center;">
                <div style="display: flex; align-items: center; margin-bottom: 2px;">
                    <i class="fas fa-share-alt" style="margin-right: 5px; font-size: 12px;"></i>
                    <span style="font-size: 13px; font-weight: bold;">${folderName}</span>
                </div>
                <div style="display: flex; align-items: center; font-size: 10px; opacity: 0.9;">
                    <i class="fas ${permissionIcon}" style="margin-right: 3px;"></i>
                    <span>${permissionText}</span>
                </div>
            </div>
            <div style="position: absolute; top: 3px; right: 3px; background: rgba(255,255,255,0.2); border-radius: 50%; width: 16px; height: 16px; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-cloud" style="font-size: 8px; color: white;"></i>
            </div>
        </div>
    `;
    
    // 移除其他文件夹的active状态
    document.querySelectorAll('.card-folder').forEach(folder => {
        folder.classList.remove('active');
    });
    
    // 添加点击事件
    sharedFolderEl.addEventListener('click', () => {
        accessSharedFolder(folderId);
    });
    
    // 插入到添加按钮之前
    container.insertBefore(sharedFolderEl, addButton);
}

// 专门渲染单个共享名片
//替换 share-management.js 中的 renderSharedCard 函数
//替换 share-management.js 中的 renderSharedCard 函数
function renderSharedCard(card) {
    const cardList = document.getElementById('cardList');
    const tableBody = document.getElementById('cardTableBody');
    
    // 清空容器
    cardList.innerHTML = '';
    tableBody.innerHTML = '';
    
    // 清空选中的卡片（共享模式下不应该有选中状态）
    selectedCardIds = [];
    document.getElementById('selectAll').checked = false;
    
    // 获取当前共享权限
    const permissionLevel = sharedResourceInfo ? sharedResourceInfo.permissionLevel : 'read';
    const isReadOnly = permissionLevel === 'read' || permissionLevel === 'READ';
    const hasEditPermission = !isReadOnly;
    
    // 渲染增强版共享名片 - 卡片视图
    const cardEl = document.createElement('div');
    cardEl.className = 'card-item shared-card-enhanced';
    cardEl.dataset.id = card.cardId;
    
    // 构建增强版名片内容
    cardEl.innerHTML = `
        <div class="business-card-container">
            <!-- 名片头部装饰 -->
            <div class="card-header-decoration"></div>
            
            <!-- 公司/机构信息区域 -->
            <div class="company-section">
                <div class="company-name">${card.organization || '机构名称'}</div>
                <div class="company-divider"></div>
            </div>
            
            <!-- 个人信息主区域 -->
            <div class="personal-section">
                <div class="name-title-area">
                    <h2 class="person-name">${card.name || ''}</h2>
                    <div class="person-title">${card.title || '职务'}</div>
                </div>
                
                <!-- 联系信息区域 -->
                <div class="contact-section">
                    <div class="contact-row">
                        <div class="contact-item">
                            <i class="fas fa-mobile-alt contact-icon"></i>
                            <span class="contact-text">${card.phone || '电话号码'}</span>
                        </div>
                        <div class="contact-item">
                            <i class="fas fa-envelope contact-icon"></i>
                            <span class="contact-text">${card.email || '邮箱地址'}</span>
                        </div>
                    </div>
                    ${card.address ? `
                    <div class="contact-row">
                        <div class="contact-item address-item">
                            <i class="fas fa-map-marker-alt contact-icon"></i>
                            <span class="contact-text">${card.address}</span>
                        </div>
                    </div>
                    ` : ''}
                </div>
            </div>
            
            <!-- 权限状态指示器 -->
            <div class="permission-indicator-corner">
                <i class="fas ${isReadOnly ? 'fa-eye' : 'fa-edit'}"></i>
            </div>
            
            <!-- 底部装饰 -->
            <div class="card-footer-decoration"></div>
        </div>
    `;
    
    cardList.appendChild(cardEl);
    
    // 渲染表格视图（保持不变）
    const row = document.createElement('tr');
    row.className = 'shared-card-row-clean';
    row.dataset.id = card.cardId;
    
    const editButton = hasEditPermission ? 
        `<button class="btn-link edit-card" data-id="${card.cardId}" title="编辑"><i class="fas fa-edit"></i></button>` : 
        '<span class="read-only-text">只读</span>';
    
    row.innerHTML = `
        <td><i class="fas fa-share-alt" style="color: #3b82f6;"></i></td>
        <td><strong>${card.name || ''}</strong></td>
        <td>${card.organization || ''}</td>
        <td>${card.title || ''}</td>
        <td>${card.phone || ''}</td>
        <td>${card.email || ''}</td>
        <td>
            ${editButton}
            <button class="btn-link print-card" data-id="${card.cardId}" title="打印">
                <i class="fas fa-print"></i>
            </button>
            <button class="btn-link export-card" data-id="${card.cardId}" title="导出">
                <i class="fas fa-file-export"></i>
            </button>
        </td>
    `;
    
    tableBody.appendChild(row);
    
    // 绑定事件
    cardEl.addEventListener('contextmenu', (e) => {
        e.preventDefault();
        showSharedCardContextMenu(e, card.cardId, hasEditPermission);
    });
    
    row.addEventListener('contextmenu', (e) => {
        e.preventDefault();
        showSharedCardContextMenu(e, card.cardId, hasEditPermission);
    });
    
    bindSharedCardEvents(card.cardId, hasEditPermission);
    
    if (hasEditPermission) {
        cardEl.addEventListener('dblclick', () => {
            editCard(card.cardId);
        });
    }
    
    cardEl.addEventListener('click', () => {
        showCardDetails(card.cardId);
    });
}


//显示共享名片的右键菜单
//替换 share-management.js 中的 showSharedCardContextMenu 函数
function showSharedCardContextMenu(e, cardId, hasEditPermission) {
    console.log('[DEBUG] 显示共享名片右键菜单，卡片ID:', cardId, '编辑权限:', hasEditPermission);
    
    const contextMenu = document.getElementById('contextMenu');
    contextMenu.innerHTML = '';
    
    // 根据权限构建菜单项
    const menuItems = [
        { 
            id: 'ctxViewShared', 
            icon: 'eye', 
            text: '查看详情',
            disabled: false
        },
        { 
            id: 'ctxEditShared', 
            icon: 'edit', 
            text: '编辑名片',
            disabled: !hasEditPermission
        },
        { 
            id: 'ctxPrintShared', 
            icon: 'print', 
            text: '打印名片',
            disabled: false
        },
        { 
            id: 'ctxExportShared', 
            icon: 'file-export', 
            text: '导出名片',
            disabled: false
        }
    ];
    
    menuItems.forEach(item => {
        const link = document.createElement('a');
        link.id = item.id;
        link.innerHTML = `<i class="fas fa-${item.icon} me-2"></i> ${item.text}`;
        
        if (item.disabled) {
            link.style.color = '#ccc';
            link.style.cursor = 'not-allowed';
            link.onclick = (e) => {
                e.preventDefault();
                showMessage('权限不足：只读模式下无法编辑名片', 'error');
            };
        } else {
            link.addEventListener('click', () => {
                handleSharedCardContextMenu(item.id, cardId, hasEditPermission);
            });
        }
        
        contextMenu.appendChild(link);
    });
    
    // 设置菜单位置
    contextMenu.style.top = `${e.pageY}px`;
    contextMenu.style.left = `${e.pageX}px`;
    contextMenu.style.display = 'block';
}


//替换 share-management.js 中的 handleSharedCardContextMenu 函数
function handleSharedCardContextMenu(action, cardId, hasEditPermission) {
    document.getElementById('contextMenu').style.display = 'none';
    
    switch (action) {
        case 'ctxViewShared':
            // 显示名片详情
            showCardDetails(cardId);
            break;
            
        case 'ctxEditShared':
            if (hasEditPermission) {
                editCard(cardId);
            } else {
                showMessage('权限不足：只读模式下无法编辑名片', 'error');
            }
            break;
            
        case 'ctxPrintShared':
            // 打印当前共享名片
            if (checkPermissionBeforeAction('print', '打印名片')) {
                if (confirm('是否要先预览再打印？\n点击"确定"进行预览，点击"取消"直接打印')) {
                    printCards([cardId], true);
                } else {
                    printCards([cardId], false);
                }
            }
            break;
            
        case 'ctxExportShared':
            // 导出当前共享名片
            if (checkPermissionBeforeAction('import_export', '导出')) {
                document.getElementById('exportFilename').value = `共享名片导出_${new Date().toISOString().slice(0, 10).replace(/-/g, '')}`;
                document.getElementById('exportFolderId').value = '';
                document.getElementById('exportCardIds').value = JSON.stringify([cardId]);
                updateExportScopeInfo();
                showModal('exportModal');
            }
            break;
    }
}





//新增：为共享名片绑定事件
//绑定共享名片的操作按钮事件
//替换 share-management.js 中的 bindSharedCardEvents 函数
function bindSharedCardEvents(cardId, hasEditPermission) {
    // 编辑按钮（仅表格视图中存在）
    if (hasEditPermission) {
        document.querySelectorAll(`.edit-card[data-id="${cardId}"]`).forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                editCard(cardId);
            });
        });
    }
    
    // 打印按钮
    document.querySelectorAll(`.print-card[data-id="${cardId}"]`).forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            if (checkPermissionBeforeAction('print', '打印名片')) {
                if (confirm('是否要先预览再打印？')) {
                    printCards([cardId], true);
                } else {
                    printCards([cardId], false);
                }
            }
        });
    });
    
    // 导出按钮
    document.querySelectorAll(`.export-card[data-id="${cardId}"]`).forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            if (checkPermissionBeforeAction('import_export', '导出')) {
                document.getElementById('exportFilename').value = `共享名片导出_${new Date().toISOString().slice(0, 10).replace(/-/g, '')}`;
                document.getElementById('exportFolderId').value = '';
                document.getElementById('exportCardIds').value = JSON.stringify([cardId]);
                updateExportScopeInfo();
                showModal('exportModal');
            }
        });
    });
}

//显示名片详情（新增函数）
//替换 share-management.js 中的 showCardDetails 函数
function showCardDetails(cardId) {
    showLoader();
    
    fetch(`BusinessCardServlet?action=getCardById&cardId=${cardId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(card => {
            hideLoader();
            
            // 创建优化的详情模态框，使用模板字符串
            const detailsHtml = `
                <div id="cardDetailsModal" class="modal" style="display: block;">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h2><i class="fas fa-id-card"></i> 名片详情</h2>
                            <span class="close" onclick="hideModal('cardDetailsModal')">&times;</span>
                        </div>
                        <div class="card-detail-clean">
                            <div class="detail-header">
                                <h2 class="detail-name">${card.name || ''}</h2>
                                <div class="detail-basic">
                                    <span class="detail-org">${card.organization || ''}</span>
                                    <span class="detail-title">${card.title || ''}</span>
                                </div>
                            </div>
                            <div class="detail-info">
                                <div class="detail-section">
                                    <h4><i class="fas fa-user"></i> 基本信息</h4>
                                    <div class="detail-grid">
                                        <div class="detail-item">
                                            <span class="detail-label">性别:</span>
                                            <span class="detail-value">${card.gender || '未填写'}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="detail-section">
                                    <h4><i class="fas fa-phone"></i> 联系方式</h4>
                                    <div class="detail-grid">
                                        <div class="detail-item">
                                            <span class="detail-label">电话:</span>
                                            <span class="detail-value">${card.phone || '未填写'}</span>
                                        </div>
                                        <div class="detail-item">
                                            <span class="detail-label">邮箱:</span>
                                            <span class="detail-value">${card.email || '未填写'}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="detail-section">
                                    <h4><i class="fas fa-map-marker-alt"></i> 地址信息</h4>
                                    <div class="detail-grid">
                                        <div class="detail-item full-width">
                                            <span class="detail-label">机构地址:</span>
                                            <span class="detail-value">${card.address || '未填写'}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn btn-primary" onclick="hideModal('cardDetailsModal')">
                                <i class="fas fa-check"></i> 确定
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            // 移除可能存在的旧模态框
            const existingModal = document.getElementById('cardDetailsModal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // 添加到页面
            document.body.insertAdjacentHTML('beforeend', detailsHtml);
            
        })
        .catch(error => {
            hideLoader();
            console.error('获取名片详情失败:', error);
            showMessage('获取名片详情失败，请重试', 'error');
        });
}


// 更新UI为共享模式 - 修复版
//替换 share-management.js 中的 updateUIForSharedMode 函数
function updateUIForSharedMode(resourceType, resourceName) {
    // 更新主标题显示共享状态
    const header = document.getElementById('mainHeader');
    if (header) {
        const permissionLevel = sharedResourceInfo ? sharedResourceInfo.permissionLevel : 'read';
        const isReadOnly = permissionLevel === 'read' || permissionLevel === 'READ';
        
        // 使用模板字符串构建头部内容
        const permissionIcon = isReadOnly ? 'fa-eye' : 'fa-edit';
        const permissionText = isReadOnly ? '只读' : '可编辑';
        
        header.innerHTML = `
            <div style="display: flex; align-items: center; gap: 12px;">
                <i class="fas fa-share-alt"></i> 
                <span>共享内容: ${resourceName}</span>
                <span class="permission-badge-header ${isReadOnly ? 'read-only' : 'editable'}">
                    <i class="fas ${permissionIcon}"></i>
                    ${permissionText}
                </span>
            </div>
        `;
        header.style.background = 'linear-gradient(135deg, #ff9800, #f57c00)';
    }
    
    // 根据权限级别智能禁用操作按钮
    const permissionLevel = sharedResourceInfo ? sharedResourceInfo.permissionLevel : 'read';
    const isReadOnly = permissionLevel === 'read' || permissionLevel === 'READ';
    
    // 始终禁用的按钮（共享模式下不允许的操作）
    const alwaysDisabledButtons = [
        '#newBtn', '#addCardOne', '#addCardBatch', '#importCardBatch',
        '#addFolderBtn'
    ];
    
    // 只读模式下额外禁用的按钮
    const readOnlyDisabledButtons = [
        '#shareBtn'
    ];
    
    const buttonsToDisable = [...alwaysDisabledButtons];
    if (isReadOnly) {
        buttonsToDisable.push(...readOnlyDisabledButtons);
    }
    
    buttonsToDisable.forEach(selector => {
        const button = document.querySelector(selector);
        if (button) {
            button.disabled = true;
            button.style.opacity = '0.5';
            button.title = isReadOnly ? '只读模式下此功能不可用' : '共享模式下此功能不可用';
        }
    });
    
    // 在菜单栏添加退出共享模式的按钮
    const menuBar = document.querySelector('.menu-bar');
    if (menuBar && !document.getElementById('exitSharedBtn')) {
        const exitBtn = document.createElement('button');
        exitBtn.id = 'exitSharedBtn';
        exitBtn.className = 'btn';
        exitBtn.style.cssText = `
            background: linear-gradient(135deg, #ef4444, #dc2626) !important;
            color: white !important;
            border: none !important;
            padding: 8px 16px !important;
            border-radius: 6px !important;
            font-weight: 600 !important;
            font-size: 13px !important;
            transition: all 0.3s ease !important;
            box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3) !important;
        `;
        exitBtn.innerHTML = '<i class="fas fa-arrow-left"></i> 退出共享模式';
        exitBtn.onclick = exitSharedMode;
        
        // 插入到菜单栏的开头
        menuBar.insertBefore(exitBtn, menuBar.firstChild);
    }
    
    // 添加简化的共享模式通知栏
    const contentArea = document.querySelector('.content-area');
    if (contentArea && !document.getElementById('sharedModeNotice')) {
        const notice = document.createElement('div');
        notice.id = 'sharedModeNotice';
        notice.className = 'shared-mode-notice-clean';
        
        // 使用模板字符串构建通知内容
        const resourceTypeText = resourceType === 'CARD' ? '名片' : '名片夹';
        const permissionText = isReadOnly ? '只读访问' : '编辑权限';
        const actionText = isReadOnly ? '可以查看、打印和导出' : '可以查看、打印、编辑和导出';
        
        notice.innerHTML = `
            <i class="fas fa-info-circle"></i>
            <div style="flex: 1;">
                <strong>共享模式</strong> - 您正在查看共享的${resourceTypeText}
                <div style="font-size: 12px; margin-top: 2px; opacity: 0.9;">
                    权限级别: ${permissionText} | ${actionText}
                </div>
            </div>
        `;
        
        notice.style.cssText = `
            background: linear-gradient(135deg, #fff3cd 0%, #fef3c7 100%) !important;
            border: 1px solid #f59e0b !important;
            border-left: 4px solid #f59e0b !important;
            border-radius: 8px !important;
            padding: 12px 16px !important;
            margin-bottom: 20px !important;
            color: #92400e !important;
            display: flex !important;
            align-items: center !important;
            gap: 10px !important;
            font-weight: 500 !important;
            box-shadow: 0 2px 8px rgba(245, 158, 11, 0.1) !important;
            animation: slideInDown 0.5s ease;
        `;
        
        contentArea.insertBefore(notice, contentArea.firstChild);
    }
}




// 退出共享模式 - 修复版
//增强：退出共享模式 - 完整恢复功能
//优化的退出共享模式函数 - 清理所有UI元素
function exitSharedMode() {
    console.log('退出共享模式');
    
    // 确认退出
    if (!confirm('确定要退出共享模式吗？将返回到您的个人名片册。')) {
        return;
    }
    
    // 重置共享状态
    isInSharedMode = false;
    sharedResourceInfo = null;
    
    // 移除所有共享相关的UI元素
    const elementsToRemove = [
        '#exitSharedBtn',           // 菜单栏退出按钮
        '#sharedModeNotice',        // 共享模式通知栏
        '#floatingExitBtn'          // 浮动退出按钮
    ];
    
    elementsToRemove.forEach(selector => {
        const element = document.querySelector(selector);
        if (element) {
            element.remove();
        }
    });
    
    // 移除共享文件夹
    document.querySelectorAll('.card-folder[data-shared="true"]').forEach(folder => {
        folder.remove();
    });
    
    // 恢复原有UI状态
    const header = document.getElementById('mainHeader');
    if (header) {
        header.innerHTML = username + '维护的名片册';
        header.style.background = 'linear-gradient(135deg, #3a7bd5, #00d2ff)';
    }
    
    // 恢复按钮状态
    const buttonsToRestore = [
        '#newBtn', '#addCardOne', '#addCardBatch', '#importCardBatch',
        '#addFolderBtn', '#shareBtn', '#printBtn', '#recycleBtn'
    ];
    
    buttonsToRestore.forEach(selector => {
        const button = document.querySelector(selector);
        if (button) {
            button.disabled = false;
            button.style.opacity = '';
            button.title = '';
        }
    });
    
    // 重新加载用户自己的数据
    currentFolder = null;
    selectedCardIds = [];
    
    // 清空当前显示
    document.getElementById('cardList').innerHTML = `
        <div class="empty-message">
            <i class="fas fa-folder-open"></i>
            <p>请选择一个名片夹查看名片</p>
        </div>
    `;
    document.getElementById('cardTableBody').innerHTML = `
        <tr>
            <td colspan="7" class="text-center">
                <i class="fas fa-folder-open"></i>
                <p>请选择一个名片夹查看名片</p>
            </td>
        </tr>
    `;
    
    // 重新加载名片夹列表
    loadFolders();
    
    showMessage('已退出共享模式，欢迎回到您的个人名片册', 'success');
}

// 记录共享访问
function logShareAccess(resourceType, resourceId) {
    const formData = new FormData();
    formData.append('action', 'logAccess');
    formData.append('resourceType', resourceType);
    formData.append('resourceId', resourceId);
    
    fetch('ShareManagementServlet', {
        method: 'POST',
        body: formData
    }).catch(error => {
        console.error('记录访问日志失败:', error);
    });
}

// 检查共享通知 - 修复版
function checkShareNotifications() {
    fetch('ShareManagementServlet?action=getShareNotifications')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateNotificationBadge(data.count);
                // 可以在这里显示通知提醒
            } else {
                updateNotificationBadge(0);
            }
        })
        .catch(error => {
            console.error('检查共享通知失败:', error);
        });
}

// 更新通知徽章
function updateNotificationBadge(count) {
    let badge = document.getElementById('shareNotificationBadge');
    const shareBtn = document.getElementById('shareBtn');
    
    if (!badge && count > 0 && shareBtn) {
        badge = document.createElement('span');
        badge.id = 'shareNotificationBadge';
        badge.className = 'notification-badge';
        badge.style.cssText = `
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ef4444;
            color: white;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            font-size: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        `;
        shareBtn.style.position = 'relative';
        shareBtn.appendChild(badge);
    }
    
    if (badge) {
        if (count > 0) {
            badge.textContent = count > 99 ? '99+' : count;
            badge.style.display = 'flex';
        } else {
            badge.style.display = 'none';
        }
    }
}

//检查共享权限的辅助函数
//5. 修复 hasSharedEditPermission 函数（如果存在）
//同时修复 hasSharedEditPermission 函数的权限检查逻辑
//5. 修复 hasSharedEditPermission 函数的逻辑
function hasSharedEditPermission() {
    if (!isInSharedMode || !sharedResourceInfo) {
        return true; // 非共享模式，正常权限
    }
    
    // 获取权限级别
    const permissionLevel = sharedResourceInfo.permissionLevel;
    
    // 兼容大小写的权限检查
    const hasEdit = permissionLevel === 'edit' || permissionLevel === 'EDIT';
    
    console.log('[DEBUG] 权限检查详情:', {
        isInSharedMode: isInSharedMode,
        sharedResourceInfo: sharedResourceInfo,
        permissionLevel: permissionLevel,
        hasEdit: hasEdit
    });
    
    return hasEdit;
}


// 检查共享资源权限 - 新增函数
function checkSharedResourcePermission(action) {
    if (!isInSharedMode) {
        return true; // 非共享模式，允许所有操作
    }
    
    const permissionLevel = sharedResourceInfo ? sharedResourceInfo.permissionLevel : 'read';
    
    // 只读权限的限制
    if (permissionLevel === 'read') {
        const readOnlyActions = ['view', 'print', 'export'];
        const blockedActions = ['edit', 'delete', 'create', 'share'];
        
        if (blockedActions.includes(action)) {
            showMessage('只读权限，无法执行此操作', 'error');
            return false;
        }
    }
    
    return true;
}

// 检查编辑锁定
function checkEditLock(resourceType, resourceId, callback) {
    fetch('ShareManagementServlet?action=checkEditLock&resourceType=' + resourceType + '&resourceId=' + resourceId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                callback(data.locked, data.lockedBy);
            } else {
                callback(false, null);
            }
        })
        .catch(error => {
            console.error('检查编辑锁定失败:', error);
            callback(false, null);
        });
}

// 获取编辑锁定
function acquireEditLock(resourceType, resourceId, callback) {
    const formData = new FormData();
    formData.append('action', 'acquireEditLock');
    formData.append('resourceType', resourceType);
    formData.append('resourceId', resourceId);
    
    fetch('ShareManagementServlet', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        callback(data.success, data.message);
    })
    .catch(error => {
        console.error('获取编辑锁定失败:', error);
        callback(false, '获取编辑锁定失败');
    });
}

// 释放编辑锁定
function releaseEditLock(resourceType, resourceId) {
    const formData = new FormData();
    formData.append('action', 'releaseEditLock');
    formData.append('resourceType', resourceType);
    formData.append('resourceId', resourceId);
    
    fetch('ShareManagementServlet', {
        method: 'POST',
        body: formData
    }).catch(error => {
        console.error('释放编辑锁定失败:', error);
    });
}

// 导出共享管理功能
//6. 在 window.shareManagement 中更新函数
window.shareManagement = {
    init: initShareManagement,
    showShareDialog,
    checkEditLock,
    acquireEditLock,
    releaseEditLock,
    checkSharedResourcePermission,
    hasSharedEditPermission: hasSharedEditPermission, // 使用修复后的函数
    accessSharedResource: accessSharedResource,
    exitSharedMode: exitSharedMode
};

//7. 确保权限检查在编辑时正确工作
function checkSharedEditPermission() {
    if (!isInSharedMode) {
        return true;
    }
    
    const hasPermission = hasSharedEditPermission();
    console.log('[DEBUG] 编辑权限检查结果:', hasPermission);
    
    if (!hasPermission) {
        showMessage('只读权限，无法进行编辑操作', 'error');
    }
    
    return hasPermission;
}


//为共享模式添加专门的权限检查wrapper
function executeWithPermissionCheck(action, permissionType, callback) {
    console.log('[DEBUG] 执行权限检查:', action, permissionType);
    
    // 如果在共享模式下
    if (isInSharedMode) {
        if (action === 'edit' && !window.shareManagement.hasSharedEditPermission()) {
            showMessage('只读权限，无法执行此操作', 'error');
            return false;
        }
    } else {
        // 非共享模式，检查常规权限
        if (!checkPermissionBeforeAction(permissionType, action)) {
            return false;
        }
    }
    
    // 权限检查通过，执行回调
    if (typeof callback === 'function') {
        callback();
    }
    
    return true;
}

// 为共享名片的特殊操作提供统一接口
window.sharedCardOperations = {
    // 编辑共享名片
    editSharedCard: function(cardId) {
        executeWithPermissionCheck('edit', 'edit_card', () => {
            editCard(cardId);
        });
    },
    
    // 打印共享名片
    printSharedCard: function(cardId, withPreview = false) {
        executeWithPermissionCheck('print', 'print', () => {
            printCards([cardId], withPreview);
        });
    },
    
    // 导出共享名片
    exportSharedCard: function(cardId) {
        executeWithPermissionCheck('export', 'import_export', () => {
            document.getElementById('exportFilename').value = '共享名片导出_' + new Date().toISOString().slice(0, 10).replace(/-/g, '');
            document.getElementById('exportFolderId').value = '';
            document.getElementById('exportCardIds').value = JSON.stringify([cardId]);
            updateExportScopeInfo();
            showModal('exportModal');
        });
    },
    
    // 查看共享名片详情
    viewSharedCardDetails: function(cardId) {
        showCardDetails(cardId);
    }
};



